<template>
  <div class="app-container">
    <div v-permission="['admin']">
      <el-link :href="`${envHost}/static/upload/example.zip`" type="warning">批量导入请按照模板进行导入，点击下载</el-link>
      <div class="filter-container">
        <el-input v-model="listQuery.search" placeholder="搜索名称或图录号" style="width: 300px;margin-right: 10px; margin-top:10px" @keyup.enter.native="handleFilter">
          <el-button slot="append" icon="el-icon-search" @click="handleFilter" />
        </el-input>
        <el-button type="primary" icon="el-icon-document-add" @click="handleUpload">批量导入</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">手动添加</el-button>
        <el-button type="primary" icon="el-icon-download" :loading="exportLoading" @click="handleExport">导出成交统计表</el-button>
      </div>
    </div>
    <div v-permission="['outer', 'editor', 'cashier', 'auditor']" class="filter-container">
      <el-input v-model="listQuery.search" placeholder="搜索名称或图录号" style="width: 200px; margin-top:10px" @keyup.enter.native="handleFilter" />
      <!-- <el-select v-model="listQuery.lotid" v-permission="['outer', 'editor', 'cashier']" :loading="lotLoading" clearable filterable placeholder="专场" @change="handleFilter">
        <el-option v-for="item in lots" :key="item.id" :label="item.name" :value="item.id" />
      </el-select> -->
      <el-select v-model="listQuery.send_user" v-permission="['editor', 'cashier']" :loading="userLoading" clearable filterable placeholder="送货人姓名或手机号" @change="handleFilter">
        <el-option v-for="item in sendUsers" :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.buy_user" v-permission="['outer', 'cashier']" :loading="userLoading" clearable filterable placeholder="购买人姓名、号牌或手机号" @change="handleFilter">
        <el-option v-for="item in buyUsers" :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
      <el-button type="primary" plain icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-permission="['editor']" type="primary" icon="el-icon-plus" @click="handleAdd">拍品入库</el-button>
    </div>

    <goods-table :list-loading="listLoading" :list-data="list" @update="fetchData" />

    <div v-show="total > 0" class="pagination-container">
      <el-pagination background :current-page="listQuery.page" :page-sizes="[15, 20, 30]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :fullscreen="dialogStatus !== 'upload'" center :visible.sync="dialogFormVisible" @closed="handleDialogClose">
      <el-form ref="lotForm" class="form-goods" :rules="rules" :model="temp" label-position="left" label-width="100px">
        <el-form-item label="上传拍品" prop="file">
          <el-upload
            ref="upload"
            :action="api"
            :on-change="handleFileChange"
            :on-exceed="handleFileExceed"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            :limit="1"
            style="width: 100%; max-width: 450px"
            :auto-upload="false"
            accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <el-button slot="trigger" :disabled="fileList.length > 0" type="text">
              选取文件 &nbsp;&nbsp;&nbsp;<small>请确保文件格式符合导入模板</small>
            </el-button>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="送货人" prop="send_user">
          <el-select v-model="temp.send_user" :loading="userLoading" filterable placeholder="请选择送货人">
            <el-option v-for="item in sendUsers" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button v-if="dialogStatus === 'upload'" :loading="btnLoading" type="primary" @click="uploadGoods">上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import GoodsTable from './components/GoodsTable'
import { getAllUsers } from '@/api/user'
import { getAllLots } from '@/api/lot'
import { getGoods, batchImport, exportDealGoods } from '@/api/goods'

export default {
  name: 'GoodsManagement',
  components: { GoodsTable },
  data () {
    var validateFile = (rule, value, callback) => {
      if (this.fileList.length === 0) {
        callback(new Error('请选择拍品文件'))
      } else {
        callback()
      }
    }
    return {
      lotId: '',
      listQuery: {
        search: '',
        page: 1,
        limit: 15,
        lotid: '',
        send_user: '',
        buy_user: ''
      },
      list: [],
      total: 0,
      listLoading: true,
      userLoading: false,
      sendUsers: [],
      buyUsers: [],
      lots: [],
      lotLoading: false,
      dialogStatus: 'upload',
      textMap: {
        edit: '修改拍品',
        add: '添加拍品',
        upload: '批量导入'
      },
      api: `${process.env.VUE_APP_BASE_API}lot/upload`,
      fileList: [],
      aucData: new FormData(),
      temp: {
        send_user: ''
      },
      dialogFormVisible: false,
      btnLoading: false,
      rules: {
        file: [{ required: true, validator: validateFile, trigger: 'blur' }]
        // send_user: [{ required: true, message: '送货人不能为空', trigger: 'change' }]
      },
      exportLoading: false,
      envHost: process.env.VUE_APP_HOST
    }
  },
  created () {
    const id = this.$route.params && this.$route.params.id
    this.lotId = id
    this.listQuery.lotid = id || ''
    this.fetchData()
    this.fetchUsers()
    this.fetchLots()
  },
  activated () {
    this.fetchData()
    this.fetchUsers()
    this.fetchLots()
  },
  methods: {
    fetchData () {
      this.listLoading = true
      getGoods(this.listQuery).then(res => {
        this.list = res.data.list
        this.total = res.data.total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    fetchUsers () {
      this.userLoading = true
      getAllUsers().then(res => {
        this.sendUsers = res.data.send
        this.buyUsers = res.data.buy
        this.userLoading = false
      }).catch(err => {
        console.log(err)
        this.userLoading = false
      })
    },
    fetchLots () {
      this.lotLoading = true
      getAllLots().then(res => {
        this.lots = res.data
        this.lotLoading = false
      }).catch(err => {
        console.log(err)
        this.lotLoading = false
      })
    },
    handleUpload () {
      this.dialogStatus = 'upload'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['lotForm'].clearValidate()
      })
    },
    handleFileChange (file, fileList) {
      this.aucData.append('file', fileList[0].raw)
      this.fileList = fileList
      this.$refs['lotForm'].validate().catch(() => {})
    },
    handleFileRemove (file, fileList) {
      this.fileList = fileList
      this.aucData = new FormData()
    },
    handleFileExceed (file, fileList) {
      this.$message({
        message: '每次只能上传一个文件，如需替换请先删除已选择文件',
        type: 'error'
      })
    },
    uploadGoods () {
      this.aucData.append('lot_id', this.lotId)
      this.aucData.append('send_id', this.temp.send_user)
      this.$refs['lotForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          batchImport(this.aucData).then(res => {
            this.$notify({
              title: '成功',
              message: res.msg,
              type: 'success',
              duration: 2000
            })
            this.handleFilter()
            this.fileList = []
            this.aucData = new FormData()
            this.dialogFormVisible = false
            this.btnLoading = false
          }).catch(err => {
            this.fileList = []
            this.btnLoading = false
            console.log(err)
          })
        }
      })
    },

    handleAdd () {
      this.$router.push('/goods/add')
    },

    handleExport () {
      this.exportLoading = true
      exportDealGoods(this.lotId).then(res => {
        this.exportLoading = false
        const linka = document.createElement('a')
        // linka.download = '成交统计表'
        linka.href = res.data
        document.body.appendChild(linka)
        linka.click()
        window.URL.revokeObjectURL(linka.href)
        document.body.removeChild(linka)
      }).catch(err => {
        console.log(err)
        this.exportLoading = false
      })
    },

    handleDialogClose () {
      this.aucData = new FormData()
      this.fileList = []
    },

    handleFilter () {
      this.listQuery.page = 1
      this.fetchData()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.fetchData()
      // this.$refs.table.clearSelection()
    }
  }
}
</script>

<style lang="scss" scoped>
.form-goods {
  max-width: 500px;
  margin: auto;
}
</style>
<style lang="scss">
.el-table {
  width: fit-content;
  margin-bottom: 20px;
  .ing-row {
    background: rgb(243, 218, 210);
  }
}
.form-goods {
  .el-upload-list__item {
    transition: none !important;
  }
}
</style>
